//
//  ZYJPEGDecoder.m
//  ZYWebImage
//
//  Created by wangzhipan on 2025/3/6.
//

#import "ZYJPEGDecoder.h"
#import "UIImage+Extra.h"
#import "IZYImageCacheProtocol.h"
@interface ZYJPEGDecoder (){
    NSData *_data;
}

@end
@implementation ZYJPEGDecoder
- (instancetype)initWithData:(NSData *)data
{
    if (self = [super init]) {
        _data = data;
    }
    return self;
}

- (UIImage *)decodeImage
{
    NSData *data = _data;
    if (!data || data.length == 0) {
        return nil;
    }
    CGFloat scale = MAX(1, [UIScreen mainScreen].scale);
    
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    
    
    // 先获取图片信息
    CFDictionaryRef imagePropsRef = CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
    NSDictionary *properties = (__bridge NSDictionary *)imagePropsRef;
    NSNumber *width = properties[(NSString *)kCGImagePropertyPixelWidth];
    NSNumber *height = properties[(NSString *)kCGImagePropertyPixelHeight];
    // 设置解码选项
    NSDictionary *options = @{
            (NSString *)kCGImageSourceCreateThumbnailWithTransform: @(YES),
            (NSString *)kCGImageSourceShouldCache: @(YES),
            (NSString *)kCGImageSourceThumbnailMaxPixelSize: @(MAX(width.intValue, height.intValue) * scale)
    };
    
    CGImageRef decompressedImage = CGImageSourceCreateImageAtIndex(source, 0, (__bridge CFDictionaryRef)options);
    if (!decompressedImage) {
        if (imagePropsRef) {
            CFRelease(imagePropsRef);
        }
        CFRelease(source);
        NSLog(@"%s  decode error: decompressedImage is null", __func__);
        return nil;
    }
    // 转换为位图
    size_t imageW = CGImageGetWidth(decompressedImage);
    size_t imageH = CGImageGetHeight(decompressedImage);
    
    size_t scaledWidth = imageW * scale;
    size_t scaledHeight = imageH * scale;
    size_t bytesPerRow = scaledWidth * 4;
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 scaledWidth,
                                                 scaledHeight,
                                                 8,
                                                 bytesPerRow,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host);
    if (!context) {
        CGImageRelease(decompressedImage);
        CGColorSpaceRelease(colorSpace);
        if (imagePropsRef) {
            CFRelease(imagePropsRef);
        }
        CFRelease(source);
        NSLog(@"%s  decode error: context is null", __func__);
        return nil;
    }
    
    CGContextScaleCTM(context, scale, scale);
    CGContextDrawImage(context, CGRectMake(0, 0, imageW, imageH), decompressedImage);
        
    CGImageRef scaledImage = CGBitmapContextCreateImage(context);
    UIImage *result = [UIImage imageWithCGImage:scaledImage scale:scale orientation:UIImageOrientationUp];
    
    // 清理资源
    CGImageRelease(scaledImage);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(decompressedImage);
    if (imagePropsRef) {
        CFRelease(imagePropsRef);
    }
    CFRelease(source);
    result.zy_format = ZYImageFormatJpeg;
    return result;
}
@end
